'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 抢红包 
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var PlayerManager = require('../../../../libs/playerManager');
var payConf = require('../../../../config/payConf.js');
var genRewardService = require('../../../../services/genRewardService');
var rewardService = require('../../../../services/rewardService');
var roleService = require('../../../../services/roleService');
var redPacketModel = require('../../../../models/redPacketModel');
var marqueeConf = require('../../../../config/marqueeConf');
var marqueeModel = require('../../../../models/marqueeModel.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    // 红包ID
    var red_packet_id = msg.red_packet_id;

    var reward_list = [];
    var red_packet_model = null;
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                redPacketModel.getById(red_packet_id, cb);
            },
            function (model, cb) {
                red_packet_model = model;
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'accrued'], cb);
            },
            function (cb) {
                var role_model = player_manager.role;
                var red_packet_list = role_model.red_packet_list;

                if (!red_packet_model) {
                    return next(null, {
                        code: Code.PAY_INVALID_RED_PACKET_ID
                    });
                }

                if (red_packet_model.remain_num < 1) {
                    return next(null, {
                        code: Code.PAY_NO_RED_PACKET
                    });
                }

                if (!role_model.addToRedPacketPicked(red_packet_id)) {
                    return next(null, {
                        code: Code.PAY_ALREADY_RED_PACKET
                    });
                }

                var rand_min = red_packet_model.min_red_packet;
                var rand_max = red_packet_model.max_red_packet;
                if (red_packet_model.has_spec_red_packet > 0 && red_packet_model.spec_red_packet > 0) {
                    rand_max++;
                }
                var rand_val = _.random(rand_min, rand_max);
                var get_spec_red_packet = false;
                if (rand_val > red_packet_model.max_red_packet) {
                    rand_val = red_packet_model.spec_red_packet;
                    red_packet_model.has_spec_red_packet = 0;
                    get_spec_red_packet = true;
                }

                var reward_info = {
                    reward_type: red_packet_model.reward_type,
                    reward: 0,
                    reward_num: rand_val,
                    reward_value: 0,
                    hole_num: 0
                };

                red_packet_model.remain_num--;
                rewardService.addRewardToRole(player_manager, reward_info, moduleType.MDL_ACT_PAY_REWARD, operationType.OPR_ACT_PAY_REWARD_RED_PACKET);
                reward_list.push(reward_info);

                _checkPutToMarQue(get_spec_red_packet, role_model.getName(), function () {
                    red_packet_model.save(function () {
                        cb();
                    });
                });
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

var _checkPutToMarQue = function (get_spec_red_packet, role_name, cb) {
    if (!get_spec_red_packet) {
        return cb();
    }

    // 发送走马灯消息
    var marque_type = 7;
    var itme_conf = marqueeConf.getConf(marque_type);
    var item_list = marqueeConf.getMsgConf(marque_type);

    // 加入走马灯信息到数据库
    var str = item_list[0].format;
    var reg = /name/;
    var text = str.replace(reg, role_name);

    var msg = ({
        sort_id: itme_conf.priority,
        text: text,
        is_time: itme_conf.fixed_time,
        times: itme_conf.times,
        interval_time: itme_conf.time
    });

    marqueeModel.create(msg, cb);
};
